<template>
  <!-- 企业审核-->
  <div class="app-container horizontal">
    <div v-show="idShowPage">
      <el-row :gutter="40">
        <el-col v-if="fold" class="headRowClass" :span="4" :xs="24">
          <!-- 左侧企业列表城市菜单树 -->
          <div class="head-container">
            <el-input
              v-model="cityName"
              placeholder="请输入城市名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
            />
          </div>
          <div class="head-container">
            <el-tree
              ref="tree"
              :data="cityOptions"
              node-key="label"
              :props="defaultProps"
              :expand-on-click-node="false"
              :default-expand-all="false"
              :filter-node-method="filterNode"
              :highlight-current="currentColor"
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <el-col :span="fold === true?20:24" :xs="24" class="right-content">
          <el-col v-if="fold" :span="1">
            <el-row class="treeStyle el-tree-arrow">
              <i class="el-icon-arrow-left" @click="fold = false" />
            </el-row>
          </el-col>
          <el-col v-if="!fold" :span="1">
            <el-row type="flex" justify="center" class="treeStyle2 el-tree-arrow">
              <i class="el-icon-arrow-right" @click="fold = true" />
            </el-row>
          </el-col>
          <div class="form-container">
            <el-form
              ref="topForm"
              :inline="true"
              label-width="80px"
              :model="filters"
              class="selectFrom"
            >
              <el-row>
                <el-form-item label="企业名称" prop="name">
                  <el-input v-model="filters.name" size="small" clearable placeholder="请输入企业名称" />
                </el-form-item>
                <el-form-item label="审核状态" prop="checkStatus">
                  <el-select
                    v-model="filters.checkStatus"
                    placeholder="请选择审核状态"
                    clearable
                    size="small"
                  >
                    <el-option
                      v-for="(item, index) in checkStatusOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="企业类型" prop="enterpriseType">
                  <el-select
                    v-model="filters.enterpriseType"
                    placeholder="请选择企业类型"
                    clearable
                    size="small"
                  >
                    <el-option
                      v-for="dict in enterpriseTypeOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <slot name="label">
                    <i class="highLevelStyle" :class="highLevelSet===true?'el-icon-arrow-up':'el-icon-arrow-down'" @click="highLevelSet = !highLevelSet" />
                  </slot>
                </el-form-item>
              </el-row>
              <el-row v-if="highLevelSet">
                <el-form-item label="企业状态" prop="status">
                  <el-select
                    v-model="filters.status"
                    placeholder="请选择企业状态"
                    clearable
                    size="small"
                  >
                    <el-option
                      v-for="dict in statusOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="企业法人" prop="legalperson">
                  <el-input v-model="filters.legalperson" size="small" clearable placeholder="请输入企业法人" />
                </el-form-item>
                <el-form-item label="创建时间" prop="dateRange">
                  <el-date-picker
                    v-model="dateRange"
                    size="small"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    style="width:225px"
                    clearable
                  />
                </el-form-item>
              </el-row>
            </el-form>
          </div>
          <el-row :gutter="10" class="button-wrap">
            <el-col :span="1.5">
              <el-button v-clickForbidden icon="el-icon-search" size="middle" @click="handleQuery">搜索</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-clickForbidden icon="el-icon-refresh" size="middle" @click="resetQuery">重置</el-button>
            </el-col>
            <el-col v-if="filters.status !== '1'" :span="1.5">
              <el-button v-hasPermi="[`system:sysEnterprise:edit`]" size="middle" :disabled="updateDisabled" icon="el-icon-edit" @click="handleUpdate()">审核</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="[`system:sysEnterprise:init`]" size="middle" :disabled="initDisbled" icon="el-icon-s-home" @click="initEntAdd()">企业初始化</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-if="status === '0'" v-hasPermi="[`system:enterprise:disable`]" size="middle" :disabled="isStatus" icon="el-icon-star-off" @click="handleStatusChange">
                停用
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-if="status === '1'" v-hasPermi="[`system:enterprise:disable`]" size="middle" :disabled="isStatus" icon="el-icon-star-on" @click="handleStatusChange">
                启用
              </el-button>
            </el-col>
          </el-row>
          <el-table
            ref="multipleTable"
            v-loading="tableLoading"
            :data="tableData"
            class="table-list"
            stripe
            :class="highLevelSet===true ? (needTagsView===true ? 'el-body-page-roll-tag-height' : 'el-body-page-roll-height') :
              (needTagsView===true ? 'el-body-page-roll-tag' : 'el-body-page-roll')"
            style="width:100%;"
            :row-style="rowColor"
            @selection-change="handleSelectionChange"
            @row-click="rowChecked"
          >
            <el-table-column type="selection" align="center" width="38" />
            <el-table-column prop="name" label="企业名称" min-width="200" align="center" :show-overflow-tooltip="true" />
            <el-table-column prop="nature" label="企业性质" min-width="200" align="center" :show-overflow-tooltip="true" :formatter="statusFormat" />
            <el-table-column prop="contacts" label="联系人" align="center" min-width="100" />
            <el-table-column
              prop="phone"
              label="联系电话"
              min-width="150"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column prop="enterpriseType" :formatter="(row) => formatterSysEnterpriseType(row)" label="企业类型" align="center" min-width="80" />
            <el-table-column label="企业状态" min-width="80" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.status === '0'">正常</span>
                <span v-if="scope.row.status === '1'">停用</span>
              </template>
            </el-table-column>
            <el-table-column label="审核状态" min-width="100" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.checkStatus=== '0'">审核成功</span>
                <span v-if="scope.row.checkStatus=== '1'">审核失败</span>
                <span v-if="scope.row.checkStatus=== '2'">未审核</span>
                <span v-if="scope.row.checkStatus=== '3'">已初始化</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页-->
          <pagination
            :total="total"
            :page.sync="filters.pageNum"
            :limit.sync="filters.pageSize"
            @pagination="getList"
          />
          <!-- 企业审核对话框 -->
          <AuditEnterprise ref="addAudit" @childrenGetList="childrenGetList" />
        </el-col>
      </el-row>
    </div>
    <!-- 初始化 编辑和添加页面 -->
    <AddOrUpdate v-if="addOrUpdateVisible" ref="addOrUpdate" @childrenGetList="childrenGetList" />
  </div>
</template>

<script>
import { listNoPermission } from '@/api/superviseBaseInfo/typeManage/organizationType'
import { mapState } from 'vuex'
import AddOrUpdate from './components/index'
import AuditEnterprise from './components/AuditEnterprise'
import { listAudit, initialized } from '@/api/enterprise/audit'
import { updateBasis } from '@/api/enterprise/basis'
import { listRegionTree } from '@/api/common/area'
import { getDicts } from '@/api/system/dict/data'
export default {
  name: 'Audit',
  components: {
    AddOrUpdate, AuditEnterprise
  },
  data() {
    return {
      // 城市树是否显示
      fold: true,
      // 城市树选中高亮
      currentColor: false,
      treeSelected: [],
      // 搜索框
      filters: {
        city: '',
        province: '',
        status: '0',
        pageNum: 1,
        pageSize: this.fristPageSize,
        name: '',
        nature: '',
        enterpriseType: '2',
        legalperson: '',
        checkStatus: '2'
      },
      // 高级设置显示与否
      highLevelSet: false,
      // 城市名称
      cityName: '',
      // 企业列表树数据
      cityOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 分页总条数
      total: 0,
      // 选中表格对话框的存储的值
      multipleSelection: [],
      selectRow: [],
      // 数据表格存放的数据
      tableData: [],
      // 表格加载是否显示等待图标
      tableLoading: false,
      checkStatusOptions: [
        {
          label: '审核成功',
          value: '0'
        },
        {
          label: '审核失败',
          value: '1'
        },
        {
          label: '未审核',
          value: '2'
        }
      ],
      sysEnterprise: {
        id: '',
        status: '',
        idNumber: ''
      },
      status: '0',
      // 时间范围
      dateRange: [],
      // 企业状态选项
      statusOptions: [],
      // 企业类型选项
      enterpriseTypeOptions: [{ dictValue: '', dictLabel: '全部' }],
      // 审核按钮是否可用
      updateDisabled: true,
      // 初始化按钮是否可用
      initDisbled: true,
      // 启用禁用按钮是否可用
      isStatus: true,
      // 初始化弹框标识
      addOrUpdateVisible: false,
      // 整体页面标识
      idShowPage: true,
      // 父类中的方法传递到子页面
      natureData: [],
      // 企业类型
      EnterpriseType: []
    }
  },
  computed: {
    ...mapState({
      needTagsView: state => state.settings.tagsView
    }),
    // 高级搜索显示隐藏
    handleTagShow() {
      return this.highLevelSet
    }
  },
  watch: {
    cityName(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.getList()
  },
  created() {
    this.loadCityOptions()
    getDicts('sys_dept_status').then(resp => {
      this.statusOptions = resp.data.rows
    })
    getDicts('enterprise_type').then(resp => {
      this.enterpriseTypeOptions = { ...this.enterpriseTypeOptions, ...resp.data.rows }
    })
    this.getDicts('enterprise_nature').then(response => {
      this.natureData = response.data.rows
    })
    this.listEnterpriseType()
  },
  methods: {
    // 获取单位类型
    async  listEnterpriseType() {
      const { data: { rows }} = await listNoPermission()
      this.EnterpriseType = rows
    },
    // 回显单位类型
    formatterSysEnterpriseType(row) {
      if (row && row.enterpriseType) {
        if (row.enterpriseType === '2') {
          return '监管单位'
        }
        if (this.EnterpriseType.length < 0) return
        const items = this.EnterpriseType.filter(item => {
          return item.typeNum === row.enterpriseType
        })
        return items.length > 0 ? items[0].typeName : '-'
      }
    },
    // 项目状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.natureData, row.nature)
    },
    // 获取城市信息列表
    loadCityOptions() {
      listRegionTree().then(resp => {
        if (resp) {
          this.cityOptions = resp.data
        }
      })
    },
    // 企业树形数据筛选
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.filters.province = ''
      this.filters.city = ''
      this.filters.area = ''
      const { count } = data
      switch (count) {
        case 0:
          this.filters.province = data.value
          break
        case 1:
          this.filters.city = data.value
          break
        case 2:
          this.filters.area = data.value
          break
      }
      this.$nextTick(() => {
        // 使树筛选时选中的节点高亮显示
        this.currentColor = true
        this.$refs.tree.setCurrentKey(data.value)
      })
      this.getList()
    },
    childrenGetList() {
      this.getList()
    },
    // 单击每行时每行的复选框选中
    rowChecked(row) {
      const selectData = this.multipleSelection
      this.$refs.multipleTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach(item => {	// 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },
    toggleSelection() {
      this.$refs.multipleTable.clearSelection()
    },
    // 点击表格前面选框时触发的事件
    handleSelectionChange(val) {
      if (JSON.stringify(val[0]) === '{}') {
        this.$refs.multipleTable.clearSelection()
        val = []
      }
      this.multipleSelection = val
      this.isStatus = this.multipleSelection.length !== 1
      if (this.multipleSelection.length === 1) {
        this.status = this.multipleSelection[0].status
      }
      if (this.multipleSelection.length === 1) {
        if (this.multipleSelection[0].checkStatus === '0') {
          this.updateDisabled = true
        } else {
          this.updateDisabled = false
        }
      } else {
        this.updateDisabled = true
      }
      if (this.multipleSelection.length === 1) {
        if (this.multipleSelection[0].checkStatus !== '0') {
          this.initDisbled = true
        } else {
          this.initDisbled = false
        }
      } else {
        this.initDisbled = true
      }
      this.selectRow = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item, index) => {
          this.selectRow.push(this.tableData.indexOf(item))
        })
      }
      if (val.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(val.pop())
      }
    },
    rowColor({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,211,249,0.75)' }
      }
    },
    // 搜索按钮
    handleQuery() {
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.resetForm('topForm')
      this.filters.city = ''
      this.filters.province = ''
      this.dateRange = []
      this.$refs.tree.setCurrentKey()
      this.getList()
    },
    getList() {
      this.tableLoading = true
      listAudit(this.changeDateRange(this.filters, this.dateRange)).then(resp => {
        this.tableLoading = false
        if (resp) {
          this.tableData = resp.data.rows
          this.total = resp.data.total
          // this.addTaleData()
        }
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // list表格填充空白行
    addTaleData() {
      if (this.tableData.length < this.fristPageSize) {
        const arr = {}
        this.tableData.push(arr)
        this.addTaleData()
      }
    },
    // 审核操作
    handleUpdate() {
      // 获取选中行的id
      const child = this.multipleSelection
      // 主键
      const id = child[0].id
      this.$refs.addAudit.auditAdd(id)
    },
    // 用户状态修改
    handleStatusChange() {
      const row = this.multipleSelection[0]
      const text = row.status === '0' ? '停用' : '启用'
      this.$confirm('确认要' + text + '' + row.name + '用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (row.status === '0') {
            row.status = '1'
          } else {
            row.status = '0'
          }
          this.sysEnterprise.id = row.id
          this.sysEnterprise.status = row.status
          this.sysEnterprise.idNumber = row.idNumber
          updateBasis(this.sysEnterprise).then(resp => {
            if (resp) {
              this.getList()
              this.msgSuccess('操作成功！')
            }
          })
        })
        .catch(() => {
          this.msgInfo('已取消')
        })
    },
    // 企业初始化新增
    initEntAdd() {
      const child = this.multipleSelection
      // 企业id
      const enterpriseId = child[0].id
      // 分公司id
      const subCompany = child[0].id
      initialized(enterpriseId, subCompany).then(resp => {
        if (resp) {
          const data = resp.data.Initialized
          if (data) {
            // 企业已经初始化
            return this.msgError('企业已经初始化！')
          } else {
            const id = child[0].id
            const name = child[0].name
            this.addOrUpdateVisible = true
            this.idShowPage = false
            this.$nextTick(() => {
              this.$refs.addOrUpdate.addFrom(id, name)
            })
          }
        }
      })
    }
  }
}
</script>

<style>
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    height:30px; line-height:30px;
    text-align: left;
    padding-left: 10px;
    font-size: 14px;
    font-weight:bolder;
    margin-bottom: 20px;
  }
  .bg-purple {
    background: #FFEEDD;
    color:#0a2140;
  }
</style>
